package com.msh.job;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.msh.common.VMSystem;
import com.msh.config.TopicConfig;
import com.msh.contract.SupplyCfg;
import com.msh.contract.SupplyChannel;
import com.msh.emq.MqttProducer;
import com.msh.entity.ChannelEntity;
import com.msh.entity.VendingMachineEntity;
import com.msh.feignService.TaskService;
import com.msh.service.VendingMachineService;
import com.msh.utils.JsonUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author :zhangchuanfu
 * @Date :2023/1/12
 * @Time :23:36
 * @description :补货定时扫描
 */
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vmService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private MqttProducer mqttProducer;
    /**
     * 扫描所有运营状态的售货机
     * @param param
     * @return
     */
    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyJobHandler(String param) {
        //获取分片总数和当前分片索引
        ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
        int numbers = shardingVO.getTotal();//分片总数
        int index = shardingVO.getIndex();//当前分片索引
        log.info("分片参数 当前分片参数{} 总分片数{}",index,numbers);
        XxlJobLogger.log("分片参数 当前分片参数{} 总分片数{}",index,numbers);


        //警戒线比例值
        Integer percent = taskService.getSupplyAlertValue();
        //查看所有运营状态的售货机
        LambdaQueryWrapper<VendingMachineEntity> eq = Wrappers.<VendingMachineEntity>lambdaQuery()
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id,"+numbers+") = "+ index);
        List<VendingMachineEntity> vmList = vmService.list(eq);
        vmList.forEach(vm->{
            XxlJobLogger.log("扫描售货机" + vm.getInnerCode());
            //扫描售货机货道得到缺货货道列表
            List<ChannelEntity> channelList = vmService.inventory(percent, vm);
            //int count = ;
            if (channelList.size() <= 0) return;

            XxlJobLogger.log("售货机" + vm.getInnerCode() + "缺货，自动创建补货工单");
            //补根据缺货的货道构建补货列表
            List<SupplyChannel> supplyChannels = channelList.stream().map(c->{
                SupplyChannel supplyChannel = new SupplyChannel();
                supplyChannel.setChannelId(c.getChannelCode());//货道编号
                supplyChannel.setCapacity(c.getMaxCapacity() - c.getCurrentCapacity());//补货量
                supplyChannel.setSkuId(c.getSkuId());
                supplyChannel.setSkuName(c.getSku().getSkuName());
                supplyChannel.setSkuImage(c.getSku().getSkuImage());
                return supplyChannel;
            }).collect(Collectors.toList());

            //--发送补货消息
            //构建补货协议数据
            SupplyCfg supplyCfg = new SupplyCfg();
            supplyCfg.setInnerCode(vm.getInnerCode());
            supplyCfg.setSupplyData(supplyChannels);
            supplyCfg.setMsgType("supplyTask");

            try {
                mqttProducer.send(TopicConfig.SUPPLY_TOPIC,2,supplyCfg);
                XxlJobLogger.log("发送补货数据：" + JsonUtil.serialize(supplyCfg));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        });
        return ReturnT.SUCCESS;
    }
}
